package com.laiyizhan.cms.manager.controller;

import com.laiyizhan.cms.manager.request.AdminUserRequest;
import com.laiyizhan.cms.manager.service.IAdminUserService;
import com.laiyizhan.common.model.Admin;
import com.laiyizhan.common.model.State;
import com.laiyizhan.common.service.KvdbService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 后台用户
 * Created by folie
 */
@Controller
@RequestMapping("/admin/manager")
public class AdminUserController {

    private static final Logger log = LoggerFactory.getLogger(AdminUserController.class);

    @Autowired
    IAdminUserService adminUserService;
    @Autowired
    KvdbService kvdbService;

    /**
     * 后台登录入口
     *
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(AdminUserRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        Admin adminUser = adminUserService.checkUser(request);
        State state = new State();
        if (adminUser != null) {
            session.setAttribute("adminUser", adminUser);
            /*机构名称*/
            session.setAttribute("oName",request.getoName());
            response.sendRedirect("/admin/"+request.getType()+"/index/show");
            log.debug("登录成功, 重定向到文章管理");
            return null;
        }
        return new ModelAndView(new InternalResourceView("/login.jsp"));
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logout(HttpSession session) {
        session.removeAttribute("adminUser");
        return new ModelAndView(new InternalResourceView("/login.jsp"));
    }


}
